import axios from 'axios';

class BaiduOCR {
  constructor() {
    this.accessToken = null;
    this.tokenExpireTime = null;
    this.apiKey = process.env.BAIDU_API_KEY;
    this.secretKey = process.env.BAIDU_SECRET_KEY;
    this.tokenUrl = 'https://aip.baidubce.com/oauth/2.0/token';
    this.ocrUrl = 'https://aip.baidubce.com/rest/2.0/ocr/v1/webimage';
  }

  async getAccessToken() {
    // 检查token是否还有效（提前5分钟刷新）
    if (this.accessToken && this.tokenExpireTime && Date.now() < this.tokenExpireTime - 5 * 60 * 1000) {
      return this.accessToken;
    }
    
    try {
      console.log('获取百度AI访问令牌...');
      const response = await axios.get(this.tokenUrl, {
        params: {
          grant_type: 'client_credentials',
          client_id: this.apiKey,
          client_secret: this.secretKey
        }
      });
      
      if (response.data.error) {
        throw new Error(`获取访问令牌失败: ${response.data.error_description}`);
      }
      
      this.accessToken = response.data.access_token;
      // 设置过期时间（百度token有效期30天，我们设置29天）
      this.tokenExpireTime = Date.now() + 29 * 24 * 60 * 60 * 1000;
      
      console.log('百度AI访问令牌获取成功');
      return this.accessToken;
    } catch (error) {
      console.error('获取百度AI访问令牌失败:', error);
      throw new Error(`获取访问令牌失败: ${error.message}`);
    }
  }

  async recognizeText(imageBuffer, options = {}) {
    try {
      const accessToken = await this.getAccessToken();
      
      // 构建请求参数 - 使用base64编码
      const formData = new URLSearchParams();
      formData.append('image', imageBuffer.toString('base64'));
      
      // 添加可选参数
      if (options.language_type) {
        formData.append('language_type', options.language_type);
      }
      if (options.detect_direction) {
        formData.append('detect_direction', options.detect_direction);
      }
      if (options.detect_language) {
        formData.append('detect_language', options.detect_language);
      }
      
      console.log('开始OCR识别...');
      const response = await axios.post(
        `${this.ocrUrl}?access_token=${accessToken}`,
        formData.toString(),
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          timeout: 30000 // 30秒超时
        }
      );
      
      if (response.data.error_code) {
        throw new Error(`百度OCR错误 ${response.data.error_code}: ${response.data.error_msg}`);
      }
      
      const result = this.formatResult(response.data);
      console.log(`OCR识别完成，识别到 ${result.wordCount} 个文字`);
      
      return result;
    } catch (error) {
      console.error('OCR识别失败:', error);
      throw error;
    }
  }

  formatResult(data) {
    const words = data.words_result || [];
    const confidence = words.map(item => item.probability || 0);
    
    return {
      text: words.map(item => item.words).join('\n'),
      confidence: confidence,
      averageConfidence: confidence.length > 0 ? confidence.reduce((a, b) => a + b, 0) / confidence.length : 0,
      wordCount: words.length,
      rawResult: data,
      timestamp: new Date().toISOString()
    };
  }

  // 图片预处理：压缩和格式转换
  async preprocessImage(imageBuffer) {
    // 这里可以添加图片预处理逻辑
    // 比如压缩、格式转换、质量调整等
    // 目前直接返回原图片
    return imageBuffer;
  }

  // 批量识别
  async recognizeMultipleImages(imageBuffers, options = {}) {
    const results = [];
    const errors = [];
    
    for (let i = 0; i < imageBuffers.length; i++) {
      try {
        const result = await this.recognizeText(imageBuffers[i], options);
        results.push({
          index: i,
          success: true,
          data: result
        });
      } catch (error) {
        errors.push({
          index: i,
          success: false,
          error: error.message
        });
      }
    }
    
    return {
      results,
      errors,
      totalCount: imageBuffers.length,
      successCount: results.length,
      errorCount: errors.length
    };
  }
}

export default BaiduOCR;
